package com.fishingwithme.android.data.model

import com.google.gson.JsonDeserializationContext
import com.google.gson.JsonDeserializer
import com.google.gson.JsonElement
import java.lang.reflect.Type

class CircleMessageDeserializer : JsonDeserializer<CircleMessage<*>> {
    override fun deserialize(
        json: JsonElement,
        typeOfT: Type,
        context: JsonDeserializationContext
    ): CircleMessage<*> {
        val jsonObject = json.asJsonObject

        val id = jsonObject.get("id").asString
        val cityCode = jsonObject.get("cityCode").asString
        val messageType = jsonObject.get("messageType").asString
        val subtype = jsonObject.get("subtype").asString
        val timestamp = jsonObject.get("timestamp").asString
        val priority = jsonObject.get("priority").asInt
        val cursor = jsonObject.get("cursor").asString

        val jsonContent = jsonObject.get("content").asJsonObject
        val content: Any = when (subtype) {
            "EVT_SHOW_H" -> {
                HarvestContent(
                    id = jsonContent.get("id").asLong,
                    pictures = jsonContent.get("pics").asJsonArray.map { it -> it.asString }
                )
            }

            "EVT_N_SPOT" -> {
                SpotContent(
                    id = jsonContent.get("id").asLong,
                    pictures = jsonContent.get("pics").asJsonArray.map { it -> it.asString }
                )
            }

            else -> {
                jsonObject.get("content")
            }
        }

        return CircleMessage(
            id = id,
            cityCode = cityCode,
            messageType = messageType,
            subtype = subtype,
            content = content,
            timestamp = timestamp,
            priority = priority,
            cursor = cursor
        )
    }
}